package at.fhhgb.mc.android.mfb_hgb.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.http.message.BasicNameValuePair;

import android.app.ActionBar;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import at.fhhgb.mc.android.mfb_hgb.R;
import at.fhhgb.mc.android.mfb_hgb.activity.dialog.DatePickerDialog;
import at.fhhgb.mc.android.mfb_hgb.activity.dialog.ProgressDialog;
import at.fhhgb.mc.android.mfb_hgb.activity.dialog.TimePickerDialog;
import at.fhhgb.mc.android.mfb_hgb.dal.InsertOffer;
import at.fhhgb.mc.android.mfb_hgb.model.TaskCaller;

public class NewOfferFragment extends Fragment implements OnTouchListener, TaskCaller {
	private ProgressDialog pDialog;
	private java.text.DateFormat dateFormat;
	private View view;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_newoffer, null);

		// Reset
		getActivity().getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

		// Set Date-EditText
		EditText dateFrom = (EditText) view.findViewById(R.id.editText_newoffer_dateFrom);
		dateFrom.setOnTouchListener(this);
		EditText dateTo = (EditText) view.findViewById(R.id.editText_newoffer_dateTo);
		dateTo.setOnTouchListener(this);

		dateFormat = DateFormat.getDateFormat(getActivity());
		String date = dateFormat.format(new Date());

		dateFrom.setText(date);
		dateTo.setText(date);

		// Set Time-EditText
		EditText timeFrom = (EditText) view.findViewById(R.id.editText_newoffer_timeFrom);
		timeFrom.setOnTouchListener(this);
		EditText timeTo = (EditText) view.findViewById(R.id.editText_newoffer_timeTo);
		timeTo.setOnTouchListener(this);

		Calendar c = Calendar.getInstance();
		String time = String.format("%02d", c.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", c.get(Calendar.MINUTE));

		timeFrom.setText(time);
		timeTo.setText(time);

		// RadioGroup From/To
		RadioGroup test = (RadioGroup) view.findViewById(R.id.radioGroup_newoffer_fromto);
		test.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				EditText location = (EditText) view.findViewById(R.id.editText_newoffer_location);
				TextView textFromTo = (TextView) view.findViewById(R.id.textView_newoffer_fromto);

				switch (checkedId) {
				case R.id.radio_newoffer_from:
					location.setHint(getString(R.string.start));
					textFromTo.setText(getString(R.string.to));
					break;

				case R.id.radio_newoffer_to:
					location.setHint(getString(R.string.destination));
					textFromTo.setText(getString(R.string.from));
					break;
				}
			}
		});

		return view;
	}

	/**
	 * Opens the DatePicker
	 * 
	 * @param view
	 *            EditText for Date (touched)
	 */
	private void openDatePicker(View view) {
		Bundle params = new Bundle();
		Calendar cal = Calendar.getInstance();

		try {
			cal.setTime(dateFormat.parse(((EditText) view).getText().toString()));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		params.putSerializable("defaultDate", cal);
		params.putInt("editTextKey", view.getId());

		DialogFragment newFragment = new DatePickerDialog();
		newFragment.setArguments(params);
		newFragment.show(getActivity().getFragmentManager(), "datePicker");
	}

	/**
	 * Opens TimePicker
	 * 
	 * @param view
	 *            EditText for Time (touched)
	 */
	private void openTimePicker(View view) {
		Bundle params = new Bundle();
		String[] timeValues = ((EditText) view).getText().toString().split(":");
		Calendar cal = Calendar.getInstance();

		cal.set(0, 0, 0, Integer.valueOf(timeValues[0]), Integer.valueOf(timeValues[1]), 0);

		params.putSerializable("defaultTime", cal);
		params.putInt("editTextKey", view.getId());

		DialogFragment newFragment = new TimePickerDialog();
		newFragment.setArguments(params);
		newFragment.show(getActivity().getFragmentManager(), "timePicker");
	}

	@Override
	public void onBackgroundTaskCompleted(Object result) {
		if((Integer)result == 1)
		{
			FragmentManager fragmentManager = getActivity().getFragmentManager();
			FragmentTransaction ft = fragmentManager.beginTransaction();
			FragmentOverview f = new FragmentOverview();
			
			Bundle b = new Bundle();
			b.putInt("type", 1);
			f.setArguments(b);
			
			ft.replace(R.id.container, f);
			ft.commit();
		}
		else
		{
			TextView errorText = (TextView)view.findViewById(R.id.textView_newoffer_error);
			
			errorText.setText(R.string.unknown_error);
			errorText.setVisibility(TextView.VISIBLE);
		}
		
		pDialog.dismiss();
	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
			switch (arg0.getId()) {
			case R.id.editText_newoffer_dateFrom:
			case R.id.editText_newoffer_dateTo:
				openDatePicker(arg0);
				break;

			case R.id.editText_newoffer_timeFrom:
			case R.id.editText_newoffer_timeTo:
				openTimePicker(arg0);
				break;
			}
		}

		return true;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		setHasOptionsMenu(true);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);

		if (!((OverviewActivity) getActivity()).isDrawerOpened()) {
			inflater.inflate(R.menu.newoffer, menu);

			ActionBar actionBar = getActivity().getActionBar();

			actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
			actionBar.setDisplayShowTitleEnabled(true);
			actionBar.setTitle(getString(R.string.fragment_newoffer_title));
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.new_offer_accept:
			TextView errorText = (TextView)view.findViewById(R.id.textView_newoffer_error);
			errorText.setVisibility(TextView.INVISIBLE);
			
			if(((EditText)view.findViewById(R.id.editText_newoffer_location)).getText().toString().isEmpty() || ((EditText)view.findViewById(R.id.editText_newoffer_dateFrom)).getText().toString().isEmpty())
			{
				errorText.setText(R.string.newoffer_required);
				errorText.setVisibility(TextView.VISIBLE);
			}
			else
			{
				sendNewOffer();
			}
			
			return true;

		case R.id.new_offer_revert:
			((OverviewActivity) getActivity()).onBackPressed();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	private void sendNewOffer() {
		SharedPreferences prefs = getActivity().getSharedPreferences(getString(R.string.preferences_key), getActivity().MODE_PRIVATE);
		long id = prefs.getLong("id", -1);

		// error
		if (id == -1)
			return;

		// get type
		int type;
		if (((RadioGroup) view.findViewById(R.id.radioGroup_newoffer_offersearch)).getCheckedRadioButtonId() == R.id.radio_newoffer_search) {
			type = 2;
		} else {
			type = 1;
		}

		// get src/dst
		String src, dst;
		if (((RadioGroup) view.findViewById(R.id.radioGroup_newoffer_fromto)).getCheckedRadioButtonId() == R.id.radio_newoffer_from) {
			src = getString(R.string.fh_hagenberg);
			dst = ((TextView) view.findViewById(R.id.editText_newoffer_location)).getText().toString();
		} else {
			src = ((TextView) view.findViewById(R.id.editText_newoffer_location)).getText().toString();
			dst = getString(R.string.fh_hagenberg);
		}

		// over TODO
		String over = ((TextView)view.findViewById(R.id.editText_newoffer_over)).getText().toString();

		// start time
		SimpleDateFormat sqlDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");

		// Save date in Calendar-Object
		Calendar fromCal = Calendar.getInstance();
		try {
			String[] fromTime = ((EditText)view.findViewById(R.id.editText_newoffer_timeFrom)).getText().toString().split(":");
			
			fromCal.setTime(dateFormat.parse(((EditText) view.findViewById(R.id.editText_newoffer_dateFrom)).getText().toString()));
			fromCal.set(fromCal.get(Calendar.YEAR), fromCal.get(Calendar.MONTH), fromCal.get(Calendar.DAY_OF_MONTH), Integer.valueOf(fromTime[0]), Integer.valueOf(fromTime[1]));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		// end time
		// Save date in Calendar-Object
		Calendar toCal = Calendar.getInstance();
		try {
			String[] toTime = ((EditText)view.findViewById(R.id.editText_newoffer_timeTo)).getText().toString().split(":");
			
			toCal.setTime(dateFormat.parse(((EditText) view.findViewById(R.id.editText_newoffer_dateFrom)).getText().toString()));
			toCal.set(toCal.get(Calendar.YEAR), toCal.get(Calendar.MONTH), toCal.get(Calendar.DAY_OF_MONTH), Integer.valueOf(toTime[0]), Integer.valueOf(toTime[1]));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		// note
		String note = ((TextView) view.findViewById(R.id.editText_newoffer_notes)).getText().toString();

		pDialog = new ProgressDialog(getActivity());
		pDialog.show();	
		
		// Dates are the same of to <
		if(toCal.compareTo(fromCal) <= 1)
		{
			new InsertOffer(this).execute(new BasicNameValuePair("UserID", String.valueOf(id)), new BasicNameValuePair("Type", String.valueOf(type)), new BasicNameValuePair("Source", src), new BasicNameValuePair("Destination", dst), new BasicNameValuePair("Over", over), new BasicNameValuePair("DepartureFrom", sqlDateFormatter.format(fromCal.getTime())),
				new BasicNameValuePair("Note", note), new BasicNameValuePair("Over", over));
		}
		else
		{
			new InsertOffer(this).execute(new BasicNameValuePair("UserID", String.valueOf(id)), new BasicNameValuePair("Type", String.valueOf(type)), new BasicNameValuePair("Source", src), new BasicNameValuePair("Destination", dst), new BasicNameValuePair("Over", over), new BasicNameValuePair("DepartureFrom", sqlDateFormatter.format(fromCal.getTime())),
				new BasicNameValuePair("DepartureTo", sqlDateFormatter.format(toCal.getTime())), new BasicNameValuePair("Note", note), new BasicNameValuePair("Over", over));
		}
	}
}
